package com.smh.demo1.a12;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;

/**
 * @author shiminghui
 * @date 2025/4/16 18:50
 * @description: TODO
 */
public class TestAspect {

    public static void main(String[] args) {

        // 准备一个切点
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(* com.smh.demo1.a12.TestAspect.Target.*(..))");

        // 准备一个通知
        MethodInterceptor methodInterceptor = new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                System.out.println("before");
                Object o = invocation.proceed();
                System.out.println("after");
                return o;

            }
        };

        // 准备一个切面
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, methodInterceptor);

        /**
         *
         * 1 ProxyTargetClass = false  看是否实现了接口, 如果实现了接口,则使用JDK动态代理,否则使用CGLIB代理
         * 2 ProxyTargetClass = true  使用CGLIB代理
         *
         */

        // 创建代理类
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(new Target());
        proxyFactory.addAdvisor(advisor);
        proxyFactory.setInterfaces(Target.class.getInterfaces());
        proxyFactory.setProxyTargetClass(true); // 使用CGLIB代理
        System.out.println("proxyFactory.getProxy() = " + proxyFactory.getProxy().getClass());
        Inter proxy = (Inter) proxyFactory.getProxy();
        proxy.read(1);

    }

    interface Inter {
        public void read(int sum);
    }

    static class Target implements Inter {
        @Override
        public void read(int sum) {
            System.out.println("Target: " + sum);
        }

        public void test() {
            System.out.println("test");
        }
    }

    static class Target2 {
        public void read(int sum) {
            System.out.println("Target2.: " + sum);
        }

        public void test() {
            System.out.println("test");
        }
    }


}
